﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using ERP_SaaS_WinForm.生产计划_派单_车间.ProductPlan;
using ERP_SaaS_WinForm.生产计划_派单_车间.ProductionOrders;
using ERP_SaaS_WinForm.生产计划_派单_车间.ProductPlanDetail;
using ERP_SaaS_WinForm.生产计划_派单_车间.apiResquest;

namespace ERP_SaaS_WinForm.生产计划_派单_车间
{
    public partial class NewPlanMain : Form
    {
        private DataGridView dgvPlanList;
        private TextBox txtPlanCode;
        private TextBox txtPlanName;
        private ComboBox cboResource;

        private Button btnSearch;
        private Button btnReset;
        
        // 分页控件
        private Label lblTotalCount;
        private Label lblTotalPage;
        private Button btnFirstPage;
        private Button btnPreviousPage;
        private Button btnNextPage;
        private Button btnLastPage;
        private TextBox txtPageNumber;
        private Button btnGoPage;
        
        // 分页变量
        private int pageIndex = 1;
        private int pageSize = 15;
        private int totalCount = 0;
        private int totalPage = 0;

        public NewPlanMain()
        {
            InitializeComponent();
            InitializeForm();
            InitializeControls();
            LoadInitialData();
        }

        private void InitializeForm()
        {
            this.Text = "生产计划管理";
            this.Size = new Size(1400, 800);
            this.StartPosition = FormStartPosition.CenterScreen;
            this.FormBorderStyle = FormBorderStyle.Sizable;
            this.MaximizeBox = true;
            this.MinimizeBox = true;
        }

        private void InitializeControls()
        {
            // 创建搜索区域面板
            Panel searchPanel = new Panel
            {
                Dock = DockStyle.Top,
                Height = 80,
                BackColor = Color.FromArgb(245, 248, 250)
            };

            // 创建搜索控件
            Label lblPlanCode = new Label { Text = "计划编号:", Location = new Point(20, 25), Size = new Size(60, 20) };
            txtPlanCode = new TextBox { Location = new Point(90, 22), Size = new Size(120, 25) };

            Label lblPlanName = new Label { Text = "产品名称:", Location = new Point(230, 25), Size = new Size(60, 20) };
            txtPlanName = new TextBox { Location = new Point(300, 22), Size = new Size(120, 25) };

            Label lblResource = new Label { Text = "来源类型:", Location = new Point(440, 25), Size = new Size(60, 20) };
            cboResource = new ComboBox { Location = new Point(510, 22), Size = new Size(120, 25), DropDownStyle = ComboBoxStyle.DropDownList };

            btnSearch = new Button { Text = "查询", Location = new Point(650, 20), Size = new Size(80, 30) };
            btnReset = new Button { Text = "重置", Location = new Point(740, 20), Size = new Size(80, 30) };
            Button btnAdd = new Button { Text = "新增", Location = new Point(830, 20), Size = new Size(80, 30), BackColor = Color.FromArgb(0, 122, 204), ForeColor = Color.White };

            // 添加控件到搜索面板
            searchPanel.Controls.AddRange(new Control[] { 
                lblPlanCode, txtPlanCode, lblPlanName, txtPlanName, 
                lblResource, cboResource, 
                btnSearch, btnReset, btnAdd 
            });

            // 创建DataGridView
            dgvPlanList = new DataGridView
            {
                Dock = DockStyle.Fill,
                AllowUserToAddRows = false,
                AllowUserToDeleteRows = false,
                ReadOnly = true,
                SelectionMode = DataGridViewSelectionMode.FullRowSelect,
                MultiSelect = false,
                AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill,
                BackgroundColor = Color.White
            };

            // 创建分页面板
            Panel pagingPanel = new Panel
            {
                Dock = DockStyle.Bottom,
                Height = 50,
                BackColor = Color.FromArgb(245, 248, 250)
            };

            // 创建分页控件
            lblTotalCount = new Label { Text = "共0条", Location = new Point(20, 15), Size = new Size(80, 20) };
            lblTotalPage = new Label { Text = "第1页/共1页", Location = new Point(120, 15), Size = new Size(100, 20) };
            
            btnFirstPage = new Button { Text = "首页", Location = new Point(240, 10), Size = new Size(60, 30) };
            btnPreviousPage = new Button { Text = "上一页", Location = new Point(310, 10), Size = new Size(60, 30) };
            btnNextPage = new Button { Text = "下一页", Location = new Point(380, 10), Size = new Size(60, 30) };
            btnLastPage = new Button { Text = "尾页", Location = new Point(450, 10), Size = new Size(60, 30) };
            
            Label lblPageNumber = new Label { Text = "跳转到:", Location = new Point(530, 15), Size = new Size(50, 20) };
            txtPageNumber = new TextBox { Location = new Point(590, 12), Size = new Size(50, 25) };
            btnGoPage = new Button { Text = "跳转", Location = new Point(650, 10), Size = new Size(60, 30) };

            // 添加分页控件到面板
            pagingPanel.Controls.AddRange(new Control[] { 
                lblTotalCount, lblTotalPage, btnFirstPage, btnPreviousPage, 
                btnNextPage, btnLastPage, lblPageNumber, txtPageNumber, btnGoPage 
            });

            // 创建主容器
            Panel mainPanel = new Panel
            {
                Dock = DockStyle.Fill
            };

            mainPanel.Controls.Add(dgvPlanList);
            mainPanel.Controls.Add(pagingPanel);

            // 添加所有面板到窗体
            this.Controls.Add(mainPanel);
            this.Controls.Add(searchPanel);

            // 绑定事件
            btnSearch.Click += BtnSearch_Click;
            btnReset.Click += BtnReset_Click;
            btnAdd.Click += BtnAdd_Click;
            btnFirstPage.Click += BtnFirstPage_Click;
            btnPreviousPage.Click += BtnPreviousPage_Click;
            btnNextPage.Click += BtnNextPage_Click;
            btnLastPage.Click += BtnLastPage_Click;
            btnGoPage.Click += BtnGoPage_Click;
            dgvPlanList.CellClick += DgvPlanList_CellClick;
            dgvPlanList.CellFormatting += DgvPlanList_CellFormatting;
            dgvPlanList.CellPainting += DgvPlanList_CellPainting;

            // 初始化下拉框数据
            InitializeComboBoxes();
        }

        private void InitializeComboBoxes()
        {
            // 来源类型下拉框
            var resourceList = new List<OrderSource>
            {
                new OrderSource { Value = 0, Name = "请选择" },
                new OrderSource { Value = 1, Name = "销售订单" },
                new OrderSource { Value = 2, Name = "库存备货" },
                new OrderSource { Value = 3, Name = "其他" }
            };
            cboResource.DataSource = resourceList;
            cboResource.DisplayMember = "Name";
            cboResource.ValueMember = "Value";
            cboResource.SelectedIndex = 0;
        }

        private void LoadInitialData()
        {
            BtnSearch_Click(null, null);
        }

        private async void BtnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                string planCode = txtPlanCode.Text.Trim();
                string productName = txtPlanName.Text.Trim(); // 修改：使用产品名称查询
                string resource = cboResource.SelectedValue?.ToString();

                var parameters = new Dictionary<string, string>();
                if (!string.IsNullOrEmpty(planCode)) parameters.Add("planCode", planCode);
                if (!string.IsNullOrEmpty(productName)) parameters.Add("productName", productName); // 修改：使用productName字段
                if (!string.IsNullOrEmpty(resource) && resource != "0") parameters.Add("resource", resource);
                parameters.Add("pageIndex", pageIndex.ToString());
                parameters.Add("pageSize", pageSize.ToString());
                
                // 添加调试信息
                Console.WriteLine($"计划编号: {planCode}");
                Console.WriteLine($"产品名称: {productName}");
                Console.WriteLine($"来源类型: {resource}");

                var apiResponse = await ApiRequestHelper.GetAsync<ApiResponse>("api/Plan/GetPlan", parameters);

                if (apiResponse.Success && apiResponse.Data != null && apiResponse.Data.code == 200)
                {
                    var response = apiResponse.Data;
                    List<PlanData> planList = new List<PlanData>();
                    
                    // 改进数据解析逻辑，处理不同的返回格式
                    if (response.data != null)
                    {
                        if (response.data is List<PlanData>)
                        {
                            planList = response.data as List<PlanData>;
                        }
                        else if (response.data is Newtonsoft.Json.Linq.JArray)
                        {
                            // 如果是JArray，尝试反序列化
                            planList = JsonConvert.DeserializeObject<List<PlanData>>(response.data.ToString());
                        }
                        else
                        {
                            // 如果data不是列表类型，可能是其他格式，尝试转换
                            try
                            {
                                planList = JsonConvert.DeserializeObject<List<PlanData>>(JsonConvert.SerializeObject(response.data));
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine($"数据转换失败: {ex.Message}");
                                Console.WriteLine($"原始数据类型: {response.data?.GetType().Name}");
                                Console.WriteLine($"原始数据内容: {JsonConvert.SerializeObject(response.data)}");
                                planList = new List<PlanData>();
                            }
                        }
                    }
                    
                    Console.WriteLine($"API响应成功，返回 {planList.Count} 条数据");
                    Console.WriteLine($"API响应数据: {JsonConvert.SerializeObject(response)}");
                    dgvPlanList.DataSource = planList;

                    // 设置列显示
                    SetupDataGridViewColumns();

                    totalCount = response.totalCount;
                    totalPage = response.totalPage;

                    lblTotalCount.Text = $"共{totalCount}条";
                    lblTotalPage.Text = $"第{pageIndex}页/共{totalPage}页";

                    UpdatePagingButtons();
                }
                else
                {
                    string errorMsg = apiResponse.Success ? 
                        $"查询失败: {apiResponse.Data?.msg ?? "未知错误"}" : 
                        $"请求失败: {apiResponse.Message}";
                    ApiRequestHelper.ShowError(errorMsg);
                    dgvPlanList.DataSource = new List<PlanData>();
                }
            }
            catch (Exception ex)
            {
                ApiRequestHelper.ShowError($"查询异常: {ex.Message}");
                dgvPlanList.DataSource = new List<PlanData>();
            }
        }

        private void SetupDataGridViewColumns()
        {
            dgvPlanList.Columns.Clear();

            // 添加数据列
            dgvPlanList.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "planId",
                HeaderText = "计划ID",
                Width = 80
            });

            dgvPlanList.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "planCode",
                HeaderText = "计划编号",
                Width = 120
            });

            dgvPlanList.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "planName",
                HeaderText = "计划名称",
                Width = 150
            });

            dgvPlanList.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "resource",
                HeaderText = "来源类型",
                Width = 100
            });

            dgvPlanList.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "productName",
                HeaderText = "产品名称",
                Width = 150
            });

            dgvPlanList.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "productCode",
                HeaderText = "产品编号",
                Width = 120
            });

            dgvPlanList.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "specification",
                HeaderText = "规格型号",
                Width = 100
            });

            dgvPlanList.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "unitName",
                HeaderText = "单位",
                Width = 80
            });

            dgvPlanList.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "planNum",
                HeaderText = "计划数量",
                Width = 100
            });

            dgvPlanList.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "planStart",
                HeaderText = "计划开工时间",
                Width = 120
            });

            dgvPlanList.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "planEnd",
                HeaderText = "计划完工时间",
                Width = 120
            });

            dgvPlanList.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "requireDate",
                HeaderText = "需求日期",
                Width = 120
            });

            dgvPlanList.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "planState",
                HeaderText = "状态",
                Width = 80
            });

            // 添加操作按钮列
            dgvPlanList.Columns.Add(new DataGridViewButtonColumn
            {
                HeaderText = "修改",
                Text = "修改",
                UseColumnTextForButtonValue = true,
                Width = 60
            });



            dgvPlanList.Columns.Add(new DataGridViewButtonColumn
            {
                HeaderText = "分解",
                Text = "分解",
                UseColumnTextForButtonValue = true,
                Width = 60
            });

            // 添加详情按钮列
            dgvPlanList.Columns.Add(new DataGridViewButtonColumn
            {
                HeaderText = "详情",
                Text = "详情",
                UseColumnTextForButtonValue = true,
                Width = 60
            });
        }

        private void DgvPlanList_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.ColumnIndex < dgvPlanList.Columns.Count)
            {
                var column = dgvPlanList.Columns[e.ColumnIndex];

                // 处理来源类型列
                if (column.DataPropertyName == "resource" && e.Value != null)
                {
                    if (int.TryParse(e.Value.ToString(), out int resourceValue))
                    {
                        switch (resourceValue)
                        {
                            case 1: e.Value = "销售订单"; break;
                            case 2: e.Value = "库存备货"; break;
                            case 3: e.Value = "其他"; break;
                            default: e.Value = "未知"; break;
                        }
                        e.FormattingApplied = true;
                    }
                }

                // 处理状态列
                if (column.DataPropertyName == "planState" && e.Value != null)
                {
                    if (int.TryParse(e.Value.ToString(), out int stateValue))
                    {
                        switch (stateValue)
                        {
                            case 0: e.Value = "未分解"; break;
                            case 1: e.Value = "已分解"; break;
                            default: e.Value = "未知"; break;
                        }
                        e.FormattingApplied = true;
                    }
                }

                // 处理日期列
                if ((column.DataPropertyName == "planStart" || column.DataPropertyName == "planEnd" || column.DataPropertyName == "requireDate") && e.Value != null)
                {
                    if (DateTime.TryParse(e.Value.ToString(), out DateTime dateValue))
                    {
                        e.Value = dateValue.ToString("yyyy-MM-dd");
                        e.FormattingApplied = true;
                    }
                }
            }
        }

        private void DgvPlanList_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                var column = dgvPlanList.Columns[e.ColumnIndex];
                
                // 处理分解按钮列的禁用状态
                if (column.HeaderText == "分解" && e.RowIndex < dgvPlanList.Rows.Count)
                {
                    var row = dgvPlanList.Rows[e.RowIndex];
                    
                    // 查找状态列的索引
                    int planStateColumnIndex = -1;
                    for (int i = 0; i < dgvPlanList.Columns.Count; i++)
                    {
                        if (dgvPlanList.Columns[i].DataPropertyName == "planState")
                        {
                            planStateColumnIndex = i;
                            break;
                        }
                    }
                    
                    if (planStateColumnIndex >= 0)
                    {
                        var planStateCell = row.Cells[planStateColumnIndex];
                        
                        if (planStateCell.Value != null && int.TryParse(planStateCell.Value.ToString(), out int planState))
                        {
                            // 如果状态为已分解(1)，则禁用分解按钮
                            if (planState == 1)
                            {
                                e.Paint(e.CellBounds, DataGridViewPaintParts.All);
                                
                                // 绘制禁用的按钮样式
                                using (var brush = new SolidBrush(Color.LightGray))
                                {
                                    e.Graphics.FillRectangle(brush, e.CellBounds);
                                }
                                
                                // 绘制禁用的文字
                                using (var brush = new SolidBrush(Color.Gray))
                                using (var font = new Font(dgvPlanList.Font, FontStyle.Strikeout))
                                {
                                    var text = "分解";
                                    var size = e.Graphics.MeasureString(text, font);
                                    var x = e.CellBounds.X + (e.CellBounds.Width - size.Width) / 2;
                                    var y = e.CellBounds.Y + (e.CellBounds.Height - size.Height) / 2;
                                    e.Graphics.DrawString(text, font, brush, x, y);
                                }
                                
                                e.Handled = true;
                            }
                        }
                    }
                }
            }
        }

        private async void DgvPlanList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                var column = dgvPlanList.Columns[e.ColumnIndex];
                if (column is DataGridViewButtonColumn)
                {
                    var currentRow = dgvPlanList.Rows[e.RowIndex];
                    PlanData planData = GetPlanDataFromRow(currentRow);

                    if (column.HeaderText == "修改")
                    {
                        // 打开修改窗体
                        var updateForm = new UpdateProductPlan(planData);
                        if (updateForm.ShowDialog() == DialogResult.OK)
                        {
                            BtnSearch_Click(null, null);
                        }
                    }

                    else if (column.HeaderText == "分解")
                    {
                        // 检查状态，如果已分解则直接返回
                        if (planData.planState == 1)
                        {
                            return; // 直接返回，不执行任何操作
                        }
                        
                        if (planData.planState == 0)
                        {
                            var bomForm = new BOMForm(planData);
                            var result = bomForm.ShowDialog();
                            if (result == DialogResult.OK || bomForm.IsDecomposed)
                            {
                                await Task.Delay(1000);
                                BtnSearch_Click(null, null);
                            }
                        }
                        else
                        {
                            MessageBox.Show("该生产计划已经分解完成，无需重复分解。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    else if (column.HeaderText == "详情")
                    {
                        try
                        {
                            // 打开生产计划详情窗体
                            var detailForm = new ProductDetailMain(planData);
                            detailForm.ShowDialog();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"打开详情窗体失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
        }

        private PlanData GetPlanDataFromRow(DataGridViewRow row)
        {
            var planData = new PlanData();
            
            foreach (DataGridViewColumn col in dgvPlanList.Columns)
            {
                if (!string.IsNullOrEmpty(col.DataPropertyName))
                {
                    var cellValue = row.Cells[col.Index].Value;
                    if (cellValue != null)
                    {
                        try
                        {
                            switch (col.DataPropertyName.ToLower())
                            {
                                case "planid":
                                    planData.planId = Convert.ToInt32(cellValue);
                                    break;
                                case "plancode":
                                    planData.planCode = cellValue.ToString();
                                    break;
                                case "planname":
                                    planData.planName = cellValue.ToString();
                                    break;
                                case "resource":
                                    planData.resource = Convert.ToInt32(cellValue);
                                    break;
                                case "productname":
                                    planData.productName = cellValue.ToString();
                                    break;
                                case "productcode":
                                    planData.productCode = cellValue.ToString();
                                    break;
                                case "specification":
                                    planData.specification = cellValue.ToString();
                                    break;
                                case "unitname":
                                    planData.unitName = cellValue.ToString();
                                    break;
                                case "plannum":
                                    planData.planNum = Convert.ToInt32(cellValue);
                                    break;
                                case "planstart":
                                    if (DateTime.TryParse(cellValue.ToString(), out DateTime start))
                                        planData.planStart = start;
                                    break;
                                case "planend":
                                    if (DateTime.TryParse(cellValue.ToString(), out DateTime end))
                                        planData.planEnd = end;
                                    break;
                                case "requiredate":
                                    if (DateTime.TryParse(cellValue.ToString(), out DateTime require))
                                        planData.requireDate = require;
                                    break;
                                case "planstate":
                                    planData.planState = Convert.ToInt32(cellValue);
                                    break;
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"转换列 {col.DataPropertyName} 的值时出错: {ex.Message}");
                        }
                    }
                }
            }

            return planData;
        }

        private void BtnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                // 打开新增生产计划窗体
                var addPlanForm = new AddProductPlanForm();
                if (addPlanForm.ShowDialog() == DialogResult.OK)
                {
                    // 新增成功后刷新数据
                    BtnSearch_Click(null, null);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开新增窗体失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void BtnReset_Click(object sender, EventArgs e)
        {
            txtPlanCode.Text = string.Empty;
            txtPlanName.Text = string.Empty;
            cboResource.SelectedIndex = 0;
        }

        private void UpdatePagingButtons()
        {
            btnFirstPage.Enabled = pageIndex > 1;
            btnPreviousPage.Enabled = pageIndex > 1;
            btnNextPage.Enabled = pageIndex < totalPage;
            btnLastPage.Enabled = pageIndex < totalPage;
        }

        private void BtnFirstPage_Click(object sender, EventArgs e)
        {
            if (pageIndex != 1)
            {
                pageIndex = 1;
                BtnSearch_Click(sender, e);
            }
        }

        private void BtnPreviousPage_Click(object sender, EventArgs e)
        {
            if (pageIndex > 1)
            {
                pageIndex--;
                BtnSearch_Click(sender, e);
            }
        }

        private void BtnNextPage_Click(object sender, EventArgs e)
        {
            if (pageIndex < totalPage)
            {
                pageIndex++;
                BtnSearch_Click(sender, e);
            }
        }

        private void BtnLastPage_Click(object sender, EventArgs e)
        {
            if (pageIndex != totalPage)
            {
                pageIndex = totalPage;
                BtnSearch_Click(sender, e);
            }
        }

        private void BtnGoPage_Click(object sender, EventArgs e)
        {
            if (int.TryParse(txtPageNumber.Text, out int pageNum) && pageNum >= 1 && pageNum <= totalPage)
            {
                pageIndex = pageNum;
                BtnSearch_Click(sender, e);
            }
            else
            {
                MessageBox.Show("请输入有效的页码。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

                 /// <summary>
         /// 安全刷新数据，避免数据解析错误
         /// </summary>
         private async Task RefreshDataSafely()
         {
             try
             {
                 string planCode = txtPlanCode.Text.Trim();
                 string productName = txtPlanName.Text.Trim();
                 string resource = cboResource.SelectedValue?.ToString();

                 var parameters = new Dictionary<string, string>();
                 if (!string.IsNullOrEmpty(planCode)) parameters.Add("planCode", planCode);
                 if (!string.IsNullOrEmpty(productName)) parameters.Add("productName", productName);
                 if (!string.IsNullOrEmpty(resource) && resource != "0") parameters.Add("resource", resource);
                 parameters.Add("pageIndex", pageIndex.ToString());
                 parameters.Add("pageSize", pageSize.ToString());

                 var apiResponse = await ApiRequestHelper.GetAsync<ApiResponse>("api/Plan/GetPlan", parameters);

                 if (apiResponse.Success && apiResponse.Data != null && apiResponse.Data.code == 200)
                 {
                     var response = apiResponse.Data;
                     List<PlanData> planList = new List<PlanData>();

                     // 更安全的数据解析
                     if (response.data != null)
                     {
                         try
                         {
                             if (response.data is List<PlanData>)
                             {
                                 planList = response.data as List<PlanData>;
                             }
                             else if (response.data is Newtonsoft.Json.Linq.JArray)
                             {
                                 planList = JsonConvert.DeserializeObject<List<PlanData>>(response.data.ToString());
                             }
                             else
                             {
                                 // 尝试直接反序列化
                                 var jsonString = JsonConvert.SerializeObject(response.data);
                                 planList = JsonConvert.DeserializeObject<List<PlanData>>(jsonString);
                             }
                         }
                         catch (Exception ex)
                         {
                             Console.WriteLine($"数据解析失败，使用空列表: {ex.Message}");
                             planList = new List<PlanData>();
                         }
                     }

                     // 更新UI
                     dgvPlanList.DataSource = planList;
                     SetupDataGridViewColumns();

                     totalCount = response.totalCount;
                     totalPage = response.totalPage;

                     lblTotalCount.Text = $"共{totalCount}条";
                     lblTotalPage.Text = $"第{pageIndex}页/共{totalPage}页";

                     UpdatePagingButtons();
                 }
                 else
                 {
                     Console.WriteLine("刷新数据失败，但删除操作已成功");
                     // 不显示错误消息，因为删除操作已经成功
                 }
             }
             catch (Exception ex)
             {
                 Console.WriteLine($"刷新数据异常: {ex.Message}");
                 throw; // 重新抛出异常，让调用者处理
             }
         }

         /// <summary>
         /// 删除生产计划
         /// </summary>
         /// <param name="planId">计划ID</param>
         /// <param name="planCode">计划编号</param>
         private async Task DeletePlanAsync(int planId, string planCode)
        {
            try
            {
                Console.WriteLine($"=== 开始删除生产计划 ===");
                Console.WriteLine($"DeletePlanAsync被调用，参数: planId={planId}, planCode={planCode}");
                
                // 构建删除请求参数
                var deleteData = new { planId = planId };
                
                // 调用删除API
                var apiResponse = await ApiRequestHelper.PostAsync<ApiResponse>("api/Plan/DelPlan", deleteData);
                
                                 if (apiResponse.Success && apiResponse.Data != null && apiResponse.Data.code == 200)
                 {
                     // 显示成功消息
                     MessageBox.Show($"生产计划 {planCode} 删除成功！", "删除成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                     
                     // 删除成功后，提示用户手动刷新或关闭窗体重新打开
                     Console.WriteLine("删除成功，建议用户手动刷新或重新打开窗体查看最新数据");
                     
                     // 可选：询问用户是否要手动刷新
                     var refreshResult = MessageBox.Show("删除成功！是否要刷新列表查看最新数据？", "刷新确认", 
                         MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                     
                     if (refreshResult == DialogResult.Yes)
                     {
                         try
                         {
                             // 延迟一下再刷新，确保后端数据已更新
                             await Task.Delay(500);
                             BtnSearch_Click(null, null);
                         }
                         catch (Exception refreshEx)
                         {
                             Console.WriteLine($"刷新数据时出现异常: {refreshEx.Message}");
                             MessageBox.Show("刷新失败，请关闭窗体重新打开查看最新数据。", "提示", 
                                 MessageBoxButtons.OK, MessageBoxIcon.Information);
                         }
                     }
                 }
                else
                {
                    string errorMsg = apiResponse.Success ? 
                        $"删除失败: {apiResponse.Data?.msg ?? "未知错误"}" : 
                        $"请求失败: {apiResponse.Message}";
                    ApiRequestHelper.ShowError(errorMsg);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"删除生产计划异常: {ex.Message}");
                ApiRequestHelper.ShowError($"删除生产计划失败: {ex.Message}");
            }
        }
    }

    // 辅助类
    public class OrderSource
    {
        public int Value { get; set; }
        public string Name { get; set; }
    }


}
